package com.ruoyi.project.travel.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.util.Date;
import java.util.List;
import java.util.Arrays;
import java.util.Map;

import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.framework.security.service.TokenService;
import com.ruoyi.project.tool.upload.service.UploadService;
import com.ruoyi.project.travel.domain.ScenicStat;
import com.ruoyi.project.travel.service.IScenicStatService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.travel.domain.Scenic;
import com.ruoyi.project.travel.service.IScenicService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;


/**
 * 景区 Controller
 *
 * @author HYD
 * @date 2020-06-14
 */
@RestController
@RequestMapping("/travel/scenic" )
public class ScenicController extends BaseController {
    @Autowired
    private IScenicService scenicService;

    @Autowired
    private IScenicStatService scenicStatService;

    @Autowired
    private UploadService uploadService;

    @Autowired
    private TokenService tokenService;

    /**
     * 查询景区 列表
     */
    @PreAuthorize("@ss.hasPermi('travel:scenic:list')" )
    @GetMapping("/list" )
    public TableDataInfo list(Scenic scenic) {
        startPage();
        QueryWrapper<Scenic> queryWrapper = new QueryWrapper<Scenic>();
        if(scenic.getName() != null && scenic.getName() != ""){
            queryWrapper.like("name",scenic.getName());
        }
        if(scenic.getStartTime() != null){
            queryWrapper.eq("start_time",scenic.getStartTime());
        }
        if(scenic.getFinishTime() != null){
            queryWrapper.eq("finish_time",scenic.getFinishTime());
        }
        if(scenic.getStatus() != null){
            queryWrapper.eq("status",scenic.getStatus());
        }
        if(scenic.getType() != null){
            queryWrapper.eq("type",scenic.getType());
        }
        queryWrapper.orderByDesc("create_time");
        List<Scenic> list = scenicService.list(queryWrapper);
        return getDataTable(list);
    }

    /**
     * 导出景区 列表
     */
    @PreAuthorize("@ss.hasPermi('travel:scenic:export')" )
    @Log(title = "景区 " , businessType = BusinessType.EXPORT)
    @GetMapping("/export" )
    public AjaxResult export(Scenic scenic) {
        QueryWrapper<Scenic> queryWrapper = new QueryWrapper<Scenic>(scenic);
        List<Scenic> list = scenicService.list(queryWrapper);
        ExcelUtil<Scenic> util = new ExcelUtil<Scenic>(Scenic. class);
        return util.exportExcel(list, "scenic" );
    }

    /**
     * 获取景区 详细信息
     */
    @PreAuthorize("@ss.hasPermi('travel:scenic:query')" )
    @GetMapping(value = "/{id}" )
    public AjaxResult getInfo(@PathVariable("id" ) Long id) {
        return AjaxResult.success(scenicService.getById(id));
    }

    /**
     * 新增景区 
     */
    @Transactional
    @PreAuthorize("@ss.hasPermi('travel:scenic:add')" )
    @Log(title = "景区 " , businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(Scenic scenic,
                          @RequestParam(value = "orderImgs",required = false) MultipartFile[] orderImgs,
                          @RequestParam(value = "mainImgs",required = false) MultipartFile mainImgs
    ) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        scenic.setOperatorId(loginUser.getUser().getUserId());
        scenic.setCreateTime(new Date());
        if(mainImgs!=null) scenic.setImages(uploadService.uploadImage(mainImgs,"scenic"));
        if(orderImgs!=null) scenic.setOtherImg(uploadService.uploadImages(orderImgs,"scenic"));
        if(scenicService.save(scenic)){
            ScenicStat scenicStat = new ScenicStat();
            scenicStat.setScenicId(scenic.getId());
            return AjaxResult.success(scenicStatService.save(scenicStat) ? 1 : 0);
        }
        return AjaxResult.error("创建失败");
    }

    /**
     * 修改景区 
     */
    @PreAuthorize("@ss.hasPermi('travel:scenic:edit')" )
    @Log(title = "景区 " , businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(Scenic scenic,
                           @RequestParam(value = "orderImgs",required = false) MultipartFile[] orderImgs,
                           @RequestParam(value = "mainImgs",required = false) MultipartFile mainImgs) {

        if(mainImgs != null){
            scenic.setImages(uploadService.uploadImage(mainImgs,"scenic"));
        }
        if(orderImgs != null && orderImgs.length > 0){
            scenic.setOtherImg(((scenic.getOtherImg() != null)?scenic.getOtherImg() + ",":"") + uploadService.uploadImages(orderImgs,"scenic"));
        }
        scenic.setUpdateTime(new Date());
        return toAjax(scenicService.updateById(scenic) ? 1 : 0);
    }

    /**
     * 删除景区 
     */
    @Transactional
    @PreAuthorize("@ss.hasPermi('travel:scenic:remove')" )
    @Log(title = "景区 " , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}" )
    public AjaxResult remove(@PathVariable Long[] ids) {
        for (Long id: ids) {
            Scenic scenic = scenicService.getById(id);
            uploadService.delImage(scenic.getImages());
            uploadService.delImage(scenic.getOtherImg());
            scenicStatService.remove(new QueryWrapper<ScenicStat>().eq("scenic_id",id));
        }
        return toAjax(scenicService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }

    /**
     * 删除图片
     * @param scenicId
     * @param type 0：主图 1：其他图片
     * @param delImg 删除图片的路径
     * @param photoPath 除了删除图片剩下的路径
     * @return
     */
    @PreAuthorize("@ss.hasPermi('travel:scenic:remove')" )
    @Log(title = "删除景区图片" , businessType = BusinessType.DELETE)
    @ResponseBody
    @RequestMapping("/delImg")
    public AjaxResult delImg(@RequestBody Map<String,Object> map){
        return toAjax(scenicService.delImg(Long.parseLong(String.valueOf(map.get("scenicId"))),Integer.parseInt(String.valueOf(map.get("type"))),String.valueOf(map.get("delImg")),String.valueOf(map.get("photoPath"))));
    }


}
